import React, { useEffect, useRef, useState } from 'react'
import recentStyle from '@/styles/recent.module.scss'
import { recentAlbum } from '@/api/recent'
import { getSongDetail, getSongUrl, getLyric } from '@/api/details'
import { Card, List, Modal, Typography } from 'antd';
import { useDispatch } from 'react-redux'
import { setSongInfo } from '../../store/modules/songInfo';
import { useNavigate } from 'react-router-dom'


export default function RecentAlbum() {

    let albumData = []; //请求到的原本的数据
    const [albumList, setAlbumList] = useState([]); //歌曲列表数据
    const { Meta } = Card;
    const { Link } = Typography;
    const index = useRef(0)
    const navigate = useNavigate();

    const getRecentList = () => { //获取数据
        recentAlbum().then(res => {
            albumData = res.data.data.list;
            // console.log(albumData);
            handleList();
        })
    }

    const handleTime = time => { //处理时间戳
        const date = new Date(time);
        const Y = date.getFullYear() + '-';
        const M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
        const D = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate());
        return Y + M + D;
    }

    const handleList = () => { //将原始数据进行处理
        const list = [];
        albumData.forEach((item, i) => {
            list[i] = {};
            list[i].time = handleTime(item.playTime);
            list[i].cover = item.data.picUrl;
            list[i].artist = item.data.artist.name;
            list[i].name = item.data.name;
            list[i].id = item.resourceId;
            list[i].songs = item.data.songs;
        });
        // console.log(list);
        setAlbumList(l => list);
    }

    const playDataRef = useRef({});
    const dispatch = useDispatch();
    const getDetailData = (id) => { //获取歌曲详情并将数据传入播放器
        getSongDetail({ ids: id }).then(res => {
            playDataRef.current = {
                name: res?.data?.songs?.[0]?.al?.name,
                cover: res?.data?.songs?.[0]?.al?.picUrl,
                artist: res?.data?.songs?.[0]?.ar
                    .map((item) => {
                        return item?.name;
                    })
                    .join(","),
            }
        });

        getLyric({ id }).then(res => {
            playDataRef.current = {
                ...playDataRef.current,
                lrc: res.data.lrc.lyric,
            }
        });

        getSongUrl({
            id,
            level: 'standard'
        }).then(res => {
            playDataRef.current = {
                ...playDataRef.current,
                url: res.data.data?.[0].url
            }
            dispatch(setSongInfo(playDataRef.current));
        });
    }

    useEffect(() => {
        getRecentList();
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [])

    const handleKey = id => {
        id += index.current;
        index.current++;
        return id;
    }

    const [getAllDetail, setGetAllDetail] = useState()
    const [isDetail, setIsDetail] = useState(false)

    const getDetail = (songs) => {//获取歌单详情

        // console.log(res);
        setGetAllDetail(songs)
        // console.log('这是数据', songs);
        setIsDetail(true)
    }

    const handleArtist = arr => { //处理歌手数组
        let artist = '';
        arr.forEach((item, i) => {
            if (i === 0) {
                artist = item.name;
            } else {
                artist += ' / ';
                artist += item.name;
            }
        })
        return artist;
    }

    return (
        <div className={recentStyle.box}>
            {
                albumList.map((item) => {
                    return (<Card
                        key={handleKey(item.id)}
                        onClick={e => { getDetail(item.songs); }}
                        hoverable={true}
                        style={{
                            width: 300,
                            height: 400,
                            marginBottom: 50,
                            position: 'relative'
                        }}
                        cover={
                            <img style={{ height: '300px' }} alt="example" src={item.cover} />
                        }
                    >
                        <span className={recentStyle.time}>{item.time}</span>
                        <Meta
                            title={item.name}
                            description={`${item.artist}`}
                        />
                    </Card>)
                })
            }
            <Modal footer={null} title="歌单详情" open={isDetail} onCancel={() =>
                setIsDetail(false)} width='600px'>
                <List
                    dataSource={getAllDetail}
                    renderItem={(item) => (
                        <List.Item style={{paddingTop:'10px'}} key={handleKey(item.id)}>
                            <List.Item.Meta
                                style={{ marginLeft: '20px' }}
                                title={
                                    <p style={{ }}>
                                        <Link onClick={e => { getDetailData(item.id); navigate(`/songs/details/${item.id}`) }}>{item.name} {item.alias[0] ? item.alias[0] : ''}</Link>
                                        <span style={{ marginRight: '20px', float: 'right' }}>{handleArtist(item.artists)}</span>
                                    </p>
                                }
                            />
                        </List.Item>
                    )}
                />
            </Modal>

        </div>
    )
}
